package org.puremvc.as3.fi.core 
{
	import org.puremvc.as3.fi.interfaces.IInjectableFacade;
	import org.puremvc.as3.fi.interfaces.IFacadeInjected;
	import org.puremvc.as3.multicore.interfaces.IModel;
	import org.puremvc.as3.multicore.interfaces.IProxy;

	import flash.utils.Dictionary;

	/**
	 * @author a.fell
	 */
	public class Model implements IModel, IFacadeInjected 
	{
		protected var facade : IInjectableFacade;
		protected var multitonKey : String;
		
		protected var proxyMap : Dictionary;
		
		public function Model( key  :String ) 
		{
			multitonKey = key;
			proxyMap = new Dictionary();
			initializeModel();	
		}
		
		/**
		 * Initialize the <code>Model</code> instance.
		 * 
		 * <P>
		 * Called automatically by the constructor, this
		 * is your opportunity to initialize the Singleton
		 * instance in your subclass without overriding the
		 * constructor.</P>
		 * 
		 * @return void
		 */
		protected function initializeModel(  ) : void 
		{
		}

		public function setFacade(facade : IInjectableFacade) : void
		{
			this.facade = facade;
		}

		public function registerProxy(proxy : IProxy) : void
		{
			with( proxy as IFacadeInjected )
			{
				setFacade(facade);
			}
			
			proxy.initializeNotifier( multitonKey );
			proxyMap[ proxy.getProxyName() ] = proxy;
			proxy.onRegister();
		}
		
		public function retrieveProxy(proxyName : String) : IProxy
		{
			return proxyMap[ proxyName ];
		}
		
		public function removeProxy(proxyName : String) : IProxy
		{
			var proxy:IProxy = retrieveProxy(proxyName);
			if ( proxy ) 
			{
				proxyMap[ proxyName ] = null;
				proxy.onRemove();
				
				//our impl
				with(proxy as IFacadeInjected)
				{
					setFacade(null);
				}
				
			}
			return proxy;
		}

		public function hasProxy(proxyName : String) : Boolean
		{
			return proxyMap[ proxyName ] != null;
		}
		
		public function hasFacade() : Boolean
		{
			return facade != null;
		}
	}
}
